package com.matt.sooncleaner.web

import android.content.Context
import android.content.Intent
import android.os.Bundle
import com.matt.sooncleaner.arch.ArchActivity
import com.matt.sooncleaner.databinding.ActivityWebviewBinding

const val KEY_WEB_URL = "webUrl"
const val KEY_WEB_TITLE = "webTitle"

class WebViewActivity : ArchActivity<ActivityWebviewBinding>() {
    private var webViewUtil: WebViewUtils? = null
    private var mTitle: String? = null
    private var mUrl: String? = null

    companion object {
        fun startWebViewActivity(context: Context, url: String?, title: String? = null) {
            context.startActivity(
                Intent(context, WebViewActivity::class.java)
                    .putExtra(KEY_WEB_URL, url).putExtra(KEY_WEB_TITLE, title)
            )
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mUrl = intent.getStringExtra(KEY_WEB_URL)
        mTitle = intent.getStringExtra(KEY_WEB_TITLE)
        initViewData()
    }

    private fun initViewData() {
        if (mUrl.isNullOrEmpty()) {
            finish()
        }

        if (mTitle?.isNotEmpty() == true) {
            binding.toolbar.setTitle(mTitle)
        }
        binding.toolbar.setNavigationOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }
        webViewUtil =
            WebViewUtils(
                binding.webView,
                mUrl,
                webViewInterface = object : WebViewUtils.WebViewInterface {
                    override fun onReceivedTitle(title: String?, isForce: Boolean) {
                        runOnUiThread {
                            if (isForce && title?.isNotEmpty() == true) {
                                binding.toolbar.setTitle(title)
                            } else {
                                if (mTitle?.isNotEmpty() == true) {
                                    binding.toolbar.setTitle(mTitle)
                                } else {
                                    binding.toolbar.setTitle(title)
                                }
                            }
                        }
                    }

                    override fun finishActivity() {
                        finish()
                    }
                }
            )

    }

}